import {
  myRequesy
} from '../../request/api'
import {
  useShowToast
} from '../../commons/index'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activityId: "",
    // isSelect: false, //基础 题目
    banner: null, //banner
    title: null, //标题
    formShow: false, //Switch表单说明
    // 表单数据
    formList: [],
    finishShow: false, //结束语表单说明
    finishValue: '', //结束语值
    isSkip: 0, //提交后跳转
    appid: "", //appid
    pageUrl: "", //页面路径
    infer: "", //推文
    isAmend: false, //是否允许修改
    is_start: false,
  },
  tmier: null,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        activityId: options.id
      })
      this.getActiveList(options.id)
    }
  },


  // 获取活动详情
  getActiveList(id) {
    let that = this
    myRequesy({
      url: 'get-activity',
      data: {
        a_id: id
      }
    }).then(res => {
      if (res.code === 0) {
        let {
          banner,
          title,
          conclusion,
          description,
          is_conclusion,
          is_description,
          ret_appid,
          ret_page,
          ret_type,
          ret_url,
          is_modify,
          is_start
        } = res.data
        that.setData({
          banner,
          title,
          formShow: is_description,
          formList: description,
          finishShow: is_conclusion,
          finishValue: conclusion,
          isSkip: ret_type,
          appid: ret_appid,
          pageUrl: ret_page,
          infer: ret_url,
          isAmend: is_modify,
          is_start
        })
      }
    })
  },

  /*************基础设置函数 开始******************************************************************************** */


  //获取标题
  headleTitle(e) {
    this.setData({
      title: e.detail.value
    })
  },


  //上传banner 函数 基础设置
  headleUpBanner() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success(res) {
        const src = res.tempFiles[0].tempFilePath
        let filename = src
        let fileNames = filename.lastIndexOf("."); //取到文件名开始到最后一个点的长度
        let fileNameLength = filename.length; //取到文件名长度
        let fileFormat = filename.substring(fileNames + 1, fileNameLength); //截
        if (fileFormat === "jpg" || fileFormat === "png" || fileFormat === "jpeg") {
          //  获取裁剪图片资源后，跳转到裁剪页并携带图片
          wx.navigateTo({
            url: '/pages/upload/upload?src=' + src,
          })
          return
        }
        useShowToast('文件格式错误')
      }
    })
  },


  // 跳转到对应的题目
  handleNavSet(e) {
    if (this.data.activityId) {
      wx.navigateTo({
        url: '/pages/subject/subject?id=' + this.data.activityId
      })
    } else {
      useShowToast('请先创建活动')
    }
  },



  //Switch表单说明 函数 基础设置
  headleFormCheck(e) {
    let {
      formList
    } = this.data
    if (!formList.length) {
      formList.push({
        state: 1,
        content: null
      })
    }
    this.setData({
      formShow: e.detail.value,
      formList
    })
  },


  //向下 函数 基础设置
  headleDown(e) {
    let {
      formList
    } = this.data
    let i = e.detail
    if (i < formList.length - 1) {
      let down = formList[i]
      formList[i] = formList[i + 1]
      formList[i + 1] = down
      this.setData({
        formList
      })
    }
  },

  //向上  函数 基础设置
  headleUpward(e) {
    let i = e.detail
    let {
      formList
    } = this.data
    if (i > 0) {
      let upward = formList[i]
      formList[i] = formList[i - 1]
      formList[i - 1] = upward
      this.setData({
        formList
      })
    }
  },

  //添加  函数 基础设置
  headleAddContent(e) {
    let that = this
    let {
      formList
    } = that.data
    let index = e.detail
    if (index === 0) {
      formList.push({
        state: 1,
        content: null
      })
      that.setData({
        formList
      })
    } else if (index === 1) {
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        success(res) {
          wx.showLoading({
            title: '正在上传...',
            mask: true
          })
          that.headleCheckout(res.tempFiles[0].tempFilePath, 2) //2大图
        }
      })
    } else {
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        success(res) {
          that.headleCheckout(res.tempFiles[0].tempFilePath, 1, 0) //1大图
        }
      })
    }

  },

  // 小图预览
  headlePreview(e) {
    let {
      formList
    } = this.data
    let {
      index,
      index1
    } = e.detail
    wx.previewImage({
      current: formList[index].content[index1],
      urls: formList[index].content,
    })
  },

  // 删除 函数 基础设置
  headleDelete(e) {
    let {
      formList,
    } = this.data
    formList.splice(e.detail, 1)
    if (!formList.length) {
      this.setData({
        formShow: false
      })
    }
    this.setData({
      formList
    })

  },

  // 删除小图 函数 基础设置
  headleRemoveImg(e) {
    let {
      index,
      index1
    } = e.detail
    let {
      formList
    } = this.data
    formList[index].content.splice(index1, 1)
    if (!formList[index].content.length) {
      formList.splice(index, 1)
    }
    this.setData({
      formList
    })

  },

  //表单文本输入 函数 基础设置
  headleFormInput(e) {
    let {
      index,
      value
    } = e.detail
    let {
      formList
    } = this.data
    formList[index].content = value
    this.setData({
      formList
    })
  },

  //Switch结束语 函数 基础设置
  headleFinishCheck(e) {
    this.setData({
      finishShow: e.detail.value
    })
  },

  // 输入结束语  函数 基础设置
  headleFinishInput(e) {
    this.setData({
      finishValue: e.detail.value
    })
  },

  // 追加小图 函数 基础设置
  headleMinDrawing(e) {
    let that = this
    let {
      formList
    } = that.data
    if (formList[e.detail].content.length < 9) {
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        success(res) {
          that.headleCheckout(res.tempFiles[0].tempFilePath, 1, e.detail) //1小图
        }
      })
    }
  },

  // 提交后跳转 函数 基础设置
  headleOption(e) {
    this.setData({
      isSkip: e.detail
    })
  },

  // 跳转的方式
  headleAppid(e) {
    let {
      index
    } = e.detail.target.dataset
    let {
      value
    } = e.detail.detail
    let {
      appid,
      pageUrl,
      infer
    } = this.data
    if (index === 1) {
      appid = value
    } else if (index === 2) {
      pageUrl = value
    } else if (index === 3) {
      infer = value
    }
    this.setData({
      appid,
      pageUrl,
      infer
    })
  },

  // 是否允许修改
  headleAmendCheck(e) {
    this.setData({
      isAmend: e.detail.value
    })
  },


  // 创建
  headleSubmit(e) {
    if (this.tmier) {
      clearInterval(this.tmier)
    }
    this.tmier = setTimeout(() => {
      let {
        activityId,
        banner,
        title,
        formShow,
        formList,
        finishShow,
        finishValue,
        appid,
        pageUrl,
        infer,
        isAmend,
        isSkip
      } = this.data
      wx.showLoading({
        title: '上传中',
        mask: true
      })
      if (!banner) {
        useShowToast('请上传封面')
      } else if (!title) {
        useShowToast('请填写活动标题')
      } else if (/[\.\/\\]/.test(title)) {
        useShowToast('标题不能包含特殊字符')
      } else if (formShow && !formList[0].content) {
        useShowToast('请填写表单说明')
      } else if (finishShow && !finishValue) {
        useShowToast('请填写结束语')
      } else if (isSkip === 1 && !infer.trim()) {
        useShowToast('请输入推文链接')
      } else if (isSkip === 2 && (!appid.trim() || !pageUrl.trim())) {
        useShowToast('请输入appid和页面路径')
      } else {
        myRequesy({
          url: 'add-activity',
          data: {
            id: activityId,
            banner,
            title,
            is_description: formShow ? 1 : 0,
            description: formShow ? formList : [],
            is_conclusion: finishShow ? 1 : 0,
            conclusion: finishValue,
            ret_type: isSkip,
            ret_url: isSkip === 1 ? infer : '',
            ret_appid: isSkip === 2 ? appid : '',
            ret_page: isSkip === 2 ? pageUrl : '',
            is_modify: isAmend ? 1 : 0
          },
          method: 'POST'
        }).then(res => {
          if (res.code === 0) {
            if (!activityId) {
              wx.showToast({
                title: '创建成功',
                mask: true
              })
            } else {
              wx.switchTab({
                url: '/pages/index/index',
              })
            }
            this.setData({
              activityId: res.data.id
            })
          } else if (res.code === 4005) {
            useShowToast(res.msg)
          }
          wx.hideLoading()
        })
      }
    }, 500)

  },



  // 上传图片校验规则                                                                                                            
  headleCheckout(tempFilePaths, state, activeIndex) {
    let that = this
    let {
      formList
    } = that.data
    let filename = tempFilePaths
    let fileNames = filename.lastIndexOf("."); //取到文件名开始到最后一个点的长度
    let fileNameLength = filename.length; //取到文件名长度
    let fileFormat = filename.substring(fileNames + 1, fileNameLength); //截
    if (fileFormat === "jpg" || fileFormat === "png" || fileFormat === "jpeg") {
      if (state === 1) {
        wx.navigateTo({
          url: '/pages/tailor/tailor?src=' + filename + '&activeIndex=' + activeIndex,
        })
      } else {
        wx.uploadFile({
          url: app.globalData.Url + 'upload-activity-img',
          filePath: filename,
          name: 'file	',
          header: {
            'Authorization': wx.getStorageSync('userInfo').token
          },
          success: function (res) {
            var data = JSON.parse(res.data);
            if (data.code === 0) {
              formList.push({
                state: 2,
                content: data.data.url
              })
              wx.hideLoading()
            } else if (data.code === 4006) {
              useShowToast('不能包含铭感图片')
              wx.hideLoading()
            }
            that.setData({
              formList
            })
          },
        });
      }
    } else {
      useShowToast('文件格式错误')
      wx.hideLoading()
    }
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})